package com.china08.yxyapi.service.tifenbao.impl;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.china08.yxyapi.api.manage.stu.mystudy.tifenbao.exercise.TifenbaoExerciseJudgeController.RespModel;
import com.china08.yxyapi.entity.es.ElasticYxyQuestionBankResource;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnowTrain;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnowTrainQues;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanQues;
import com.china08.yxyapi.model.questionbank.YxyQuesBanQuestType1_2_3Model;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainQuesRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanQuesRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.china08.yxyapi.service.mg.impl.PlanExerciseServiceImpl;
import com.china08.yxyapi.service.tifenbao.TifenbaoExerciseJudgeService;
import com.china08.yxyapi.util.DateUtils;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Service
public class TifenbaoExerciseJudgeServiceImpl implements TifenbaoExerciseJudgeService {
    @Autowired
    private MongoTemplate mTemplate;
    @Autowired
    private PlanExerciseServiceImpl planExerciseServiceImpl;

    @Autowired
    private YxyHuixuePlanKnowTrainQuesRepository yxyHuixuePlanKnowTrainQuesRepository;

    @Autowired
    private YxyHuixuePlanQuesRepository yxyHuixuePlanQuesRepository;

    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;

    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;

    @Autowired
    private YxyHuixuePlanKnowTrainRepository yxyHuixuePlanKnowTrainRepository;

    @Override
    @Transactional
    public RespModel judge(String pkId, String quesId, String answer, Boolean result, String time) {
        RespModel model = new RespModel();

        ElasticYxyQuestionBankResource question = planExerciseServiceImpl.getExerciseById(quesId);
        YxyHuixuePlanKnow planKnow = yxyHuixuePlanKnowRepository.findTopByPkId(pkId);
        List<YxyHuixuePlanKnow> planKnowLst = yxyHuixuePlanKnowRepository.findByPkId(pkId);
        YxyHuixuePlan plan = yxyHuixuePlanRepository.findOne(planKnow.getPlanId());
        // 答题记录保存
        YxyHuixuePlanKnowTrain train = new YxyHuixuePlanKnowTrain();
        train.setId(plan.getStudentId() + plan.getId() + planKnow.getKnowId() + DateUtils.formatDate10(new Date()));
        train.setStudentId(plan.getStudentId());
        train.setPlanId(plan.getId());
        train.setBookContents(plan.getBookContentId());
        train.setKnowId(planKnow.getKnowId());
        train.setKnowName(planKnow.getKnowName());
        train.setCreatedDate(new Timestamp(new Date().getTime()));
        train = yxyHuixuePlanKnowTrainRepository.save(train);

        YxyHuixuePlanKnowTrainQues trainQues = new YxyHuixuePlanKnowTrainQues();
        trainQues.setTrainId(train.getId());
        trainQues.setStudentId(plan.getStudentId());
        trainQues.setPlanId(plan.getId());
        trainQues.setBookContents(plan.getBookContentId());
        trainQues.setKnowId(planKnow.getKnowId());
        trainQues.setKnowName(planKnow.getKnowName());
        trainQues.setQuesId(question.getId());
        trainQues.setCreatedDate(new Timestamp(new Date().getTime()));
        trainQues.setUseTime(time);
        // 回答是否正确
        boolean quesResult = false;
        // 题型为单选 多选 判断
        if (question.getQuesType().equals("1") || question.getQuesType().equals("2")
                || question.getQuesType().equals("3")) {
            // 正确答案
            Gson gson = new Gson();
            YxyQuesBanQuestType1_2_3Model banQuestType1_2_3Model = gson.fromJson(question.getQuesBody(),
                    YxyQuesBanQuestType1_2_3Model.class);
            String answerTrue = banQuestType1_2_3Model.getQuesAnswer().getOptions();
            // 判断是否答对
            quesResult = planExerciseServiceImpl.correctResult(answerTrue, answer);
            trainQues.setAnswerOfMy(Arrays.asList(answer.split("")));
            trainQues.setAnswerOfQues(Arrays.asList(answerTrue.split("")));
        } else {
            quesResult = result;
        }
        // 修改试题权重
        YxyHuixuePlanQues huixuePlanQues = yxyHuixuePlanQuesRepository
                .findByStudentIdAndPlanIdAndQuesId(plan.getStudentId(), plan.getId(), question.getId());
        if (huixuePlanQues == null) {
            huixuePlanQues = new YxyHuixuePlanQues();
            huixuePlanQues.setStudentId(plan.getStudentId());
            huixuePlanQues.setPlanId(plan.getId());
            huixuePlanQues.setKnowId(planKnow.getKnowId());
            huixuePlanQues.setLevel(planKnow.getLevel());
            huixuePlanQues.setQuesId(question.getId());
            huixuePlanQues.setKnows(question.getKnowIds());
            if (quesResult) {
                huixuePlanQues.setWeight(0);
            } else {
                huixuePlanQues.setWeight(4);
            }
        } else {
            if (quesResult) {
                huixuePlanQues.setWeight(0);
            } else {
                huixuePlanQues.setWeight((huixuePlanQues.getWeight() - 1) <= 0 ? 5 : (huixuePlanQues.getWeight() - 1));
            }
        }
        yxyHuixuePlanQuesRepository.save(huixuePlanQues);

        // 修改正确答题次数
        if (quesResult) {
            int passtask = planKnow.getPassTask() + 1;
            model.passTask = passtask;
            trainQues.setPassed(1);
            for (YxyHuixuePlanKnow yxyHuixuePlanKnow : planKnowLst) {
                yxyHuixuePlanKnow.setPassTask(passtask);
            }
            // 闯关成功时（该知识点完成）
            if (passtask == planKnow.getTask()) {
                // 已完成计划的知识点数量(去除重复知识点)
                DBCollection collection = mTemplate.getCollection(mTemplate.getCollectionName(YxyHuixuePlanKnow.class));
                DBObject dbObject = new BasicDBObject("plan_id", plan.getId());
                dbObject.put("progress", (double) 100);
                @SuppressWarnings("rawtypes")
                List endlist = collection.distinct("pk_id", dbObject);
                int finishCount = endlist.size();
                // 完成度计算
                Double knowrate = (double) finishCount / plan.getKnowCount();
                DecimalFormat df = new DecimalFormat("######0.0");
                double complete = Double.valueOf(df.format(knowrate * 100));
                plan.setFinishKnowCount(finishCount);
                plan.setComplete(complete);
                yxyHuixuePlanRepository.save(plan);
                // 权重初始化
                List<YxyHuixuePlanQues> huixuePlanQuesLst = yxyHuixuePlanQuesRepository
                        .findByStudentIdAndPlanIdAndKnowId(plan.getStudentId(), plan.getId(), planKnow.getKnowId());
                for (YxyHuixuePlanQues yxyHuixuePlanQues : huixuePlanQuesLst) {
                    yxyHuixuePlanQues.setWeight(5);
                    yxyHuixuePlanQuesRepository.save(yxyHuixuePlanQues);
                }
                model.status = 1;// 点击“继续练习”按钮，跳转至练习结果-知识点完成
            } else {
                model.status = 2;// 点击“继续练习”按钮，正常继续
            }
        } else {
            YxyHuixuePlanKnowTrainQues beforeEnd = yxyHuixuePlanKnowTrainQuesRepository
                    .findTopByPlanIdAndKnowIdOrderByCreatedDateDesc(plan.getStudentId(), plan.getId(),
                            planKnow.getKnowId());
            // 当该计划该知识点上一道题做错时
            if (beforeEnd != null && beforeEnd.getPassed() == 0) {
                model.status = 0;// 点击“继续练习”按钮，页面跳转至练习结果-知识点未完成
            } else {
                model.status = 2;
            }
            model.passTask = planKnow.getPassTask();
            trainQues.setPassed(0);
        }

        yxyHuixuePlanKnowRepository.save(planKnowLst);
        yxyHuixuePlanKnowTrainQuesRepository.save(trainQues);
        model.pkId = pkId;
        model.time = time;
        model.passed = trainQues.getPassed();
        model.trainQuesId = trainQues.getId();
        model.task = planKnow.getTask();
        model.knowName = planKnow.getKnowName();
        if (trainQues.getAnswerOfMy() != null) {
            model.answerOfMy = StringUtils.join(trainQues.getAnswerOfMy().toArray(), ",");
        } else {
            model.answerOfMy = "";
        }
        model.questionBody = question.getQues();
        return model;
    }

}
